/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package provider;

import Converters.NettyConverter;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**
 *
 * @author MOI
 */
class ProviderHandler extends  SimpleChannelUpstreamHandler {

    private NettyConverter p;
    public ProviderHandler(NettyConverter proxy) {
        this.p=proxy;
    }

     @Override
    public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
           p.ConvertAndSend(e.getMessage(), ctx);
        }




    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
            throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
            throws Exception {
        e.getCause().printStackTrace();
        closeOnFlush(e.getChannel());
    }


    /**
     * Closes the specified channel after all queued write requests are flushed.
     */
    static void closeOnFlush(Channel ch) {
        if (ch.isConnected()) {
            ch.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }

}
